import {
  Button,
  Form,
  Input,
  List,
  Popup,
  Image,
  Picker,
  Popover,
  Empty,
  Toast,
  ImageViewer,
} from "antd-mobile";
import styles from "./index.module.css";
import { useEffect, useState } from "react";
import { ClockCircleOutline, LeftOutline } from "antd-mobile-icons";
import request from "../../axios";
import { Select } from "antd";

interface PouopItem {
  value: boolean;
  setValue: any;
  obj: any;
  cook: any[];
  callback?: (val: any) => void;
}

const basicColumn = [
  [
    { label: "优秀", value: "4" },
    { label: "良好", value: "3" },
    { label: "及格", value: "2" },
    { label: "不及格", value: "1" },
    { label: "待评估", value: "0" },
  ],
];

const Pouops = ({ value, setValue, callback, obj, cook }: PouopItem) => {
  const [form] = Form.useForm();
  // 存储当前选中的菜品ID
  const [selectedDishId, setSelectedDishId] = useState<string | number | null>(
    null
  );
  const [visible, setVisible] = useState<boolean>(false);
  const [showImg, setShowImg] = useState<boolean>(false);

  const [hisList, setHisList] = useState<any[]>([]);

  const handleSub = (val: any) => {
    setValue(false);
    callback &&
      callback({
        ...val,
        id: obj?.id,
        dishId: selectedDishId, // 提交选中的菜品ID
        dishName: cook.find((item) => item.id === selectedDishId)?.name || "",
      });
  };

  const setTags = (item: string) => {
    const tags = form.getFieldValue("tags");
    form.setFieldValue("tags", tags + "#" + item);
    setVisible(false);
  };

  // 生成Picker数据列
  const basicColumns = [
    cook?.map((item: any) => ({
      label: item.name,
      value: item.id,
    })),
  ];

  const getIdList = async () => {
    try {
      let id =
        form.getFieldValue("dishName") && form.getFieldValue("dishName")?.length
          ? form.getFieldValue("dishName")?.[0]
          : null;
      if (!id) {
        Toast.show("请选择菜品");
        setHisList([]);
        return;
      }
      const { data } = await request.get(`/dish_tag/${id}`);
      if (data) {
        setHisList(data);
      }
      setVisible(true);
    } catch (error) {}
  };

  useEffect(() => {
    // 只有当传入的obj有有效的disId时才设置初始值
    if (obj?.dishId) {
      form.setFieldsValue({
        dishName: [obj.dishId],
      });
      setSelectedDishId(obj.dishId);
    } else {
      // 清空选择
      form.setFieldsValue({
        dishName: [],
      });
      setSelectedDishId(null);
    }

    // 其他字段保持原有逻辑
    form.setFieldsValue({
      scorePerson: obj?.scorePerson || "",
      tags: obj?.tags || "",
      personEvaluate: obj.personEvaluate ? [String(obj.personEvaluate)] : ["0"],
      wendu: obj?.dishTemperature,
    });
  }, [obj, cook]);

  return (
    <>
      <div>
        <Popup
          visible={value}
          onMaskClick={() => setValue(false)}
          onClose={() => setValue(false)}
          bodyStyle={{
            height: "95h",
            borderRadius: "12px 12px 0px 0px",
            overflow: "hidden",
          }}
        >
          <ImageViewer
            classNames={{
              mask: "customize-mask",
              body: "customize-body",
            }}
            image={obj?.dishPicture || ""}
            visible={showImg}
            onClose={() => {
              setShowImg(false);
            }}
          />
          <div className={styles.shopName}>
            <div className={styles.shopName_top}>
              <div style={{ width:'33%' }} onClick={()=>setValue(false)}><LeftOutline /></div>
              <div style={{ width:'33%',textAlign:'center' }}>菜品评估</div>
              <div style={{ width:'33%' }}></div>
            </div>
            <div className={styles.shopName_center}>
              <Form layout="horizontal" form={form} onFinish={handleSub}>
                <Image
                  src={obj?.dishPicture || ""}
                  className={styles.img}
                  fit="cover"
                  style={{ borderRadius: 8, width: "100%", height: "50%" }}
                  onClick={() => setShowImg(true)}
                />
                <List className={styles.flex_x} style={{ marginBottom: 20 }}>
                  <List.Item></List.Item>
                </List>

                <Form.Item
                  name="dishName"
                  label="菜品名称"
                  className={styles.input_title}
                >
                  <Select
                    style={{ width: "100%" }}
                    showSearch
                    optionFilterProp="label"
                    // value={'225'}
                    // defaultValue={items?.[0]?.label}
                    onSelect={(e) => {
                      setSelectedDishId(e);
                    }}
                    options={basicColumns[0]}
                  />
                  {/* <Picker
                columns={basicColumns}
                // 监听值变化
                onConfirm={(value) => {
                  // 更新选中的菜品ID
                  setSelectedDishId(value[0] as string | number);
                }}
              >
                {(items) => (
                  // 显示选中的菜品名称，没有选中时显示提示
                  <div className={styles.pickerValue}>
                    {items?.[0]?.label || "请选择菜品"}
                  </div>
                )}
              </Picker> */}
                </Form.Item>

                <Form.Item
                  name="personEvaluate"
                  label="菜品分数"
                  className={styles.input_title}
                  trigger="onConfirm"
                  onClick={(e, datePickerRef: any) => {
                    datePickerRef.current?.open();
                  }}
                >
                  <Picker columns={basicColumn}>
                    {(val) => (val?.[0] ? val?.[0]?.label : "请选择分数")}
                  </Picker>
                </Form.Item>
                <Form.Item
                  name="wendu"
                  label="菜品温度"
                  className={styles.input_title}
                >
                  <Input
                    disabled
                    type="number"
                    placeholder="菜品温度"
                    style={{ color: "black" }}
                  />
                </Form.Item>

                <Form.Item
                  name="tags"
                  label="菜品标签"
                  className={styles.input_title}
                >
                  <Input placeholder='请输入菜品标签,标签之间用"#"号隔开' />
                </Form.Item>
                <Button className={styles.button1} onClick={() => getIdList()}>
                  <ClockCircleOutline />
                  <span>历史标签</span>
                </Button>
              </Form>
            </div>

            <div className={styles.shopName_bottom}>
              <Button
                color="primary"
                size="large"
                className={styles.button}
                onClick={() => form.submit()}
              >
                确认
              </Button>
            </div>
            <Popup
              visible={visible}
              onMaskClick={() => {
                setVisible(false);
              }}
              position="right"
              bodyStyle={{ width: "60vw" }}
            >
              {hisList?.length ? (
                <List>
                  {hisList?.map((item: any) => {
                    return (
                      <List.Item onClick={() => setTags(item)}>
                        {item}
                      </List.Item>
                    );
                  })}
                </List>
              ) : (
                <Empty
                  description="暂无数据"
                  style={{ width: "100%", height: "100%" }}
                />
              )}
            </Popup>
          </div>
        </Popup>
      </div>
    </>
  );
};

export default Pouops;
